package ran.friend.manager;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ran.constants.RedisCacheConstants;
import ran.enums.ResultCode;
import ran.exception.ServiceException;
import ran.friend.domain.question.entity.Question;
import ran.friend.mapper.question.QuestionMapper;
import ran.redis.service.RedisService;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ran
 * Date: 2025-11-20
 * Time: 19:05
 */
@Component
public class QuestionRedisCacheManager {

    @Autowired
    private RedisService redisService;
    @Autowired
    private QuestionMapper questionMapper;

    // 获取Redis中数据量
    public Long getListSize() {
        return redisService.getListSize(RedisCacheConstants.QUESTION_LIST);
    }

    public void refreshCache() {
        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<Question>()
                .select(Question::getQuestionId)
                .orderByDesc(Question::getCreateTime));
        if (CollectionUtil.isEmpty(questionList)) {
            return;
        }
        // 转化为id集合
        List<Long> questionIdList = questionList.stream().map(Question::getQuestionId).toList();
        // 存储
        redisService.rightPushAll(RedisCacheConstants.QUESTION_LIST,questionIdList);
    }

    public Long preQuestion(Long questionId) {
        Long index = redisService.indexOfForList(RedisCacheConstants.QUESTION_LIST, questionId);
        // 第一道题目, 不可向前切换
        if (index == 0) {
            throw new ServiceException(ResultCode.FAILED_FIRST_QUESTION);
        }
        return redisService.indexForList(RedisCacheConstants.QUESTION_LIST,index - 1,Long.class);
    }

    public Long nextQuestion(Long questionId) {
        Long index = redisService.indexOfForList(RedisCacheConstants.QUESTION_LIST, questionId);
        Long lastIndex = getListSize() - 1;
        // 最后一道题目, 不可向后切换
        if (index >= lastIndex) {
            throw new ServiceException(ResultCode.FAILED_LAST_QUESTION);
        }
        return redisService.indexForList(RedisCacheConstants.QUESTION_LIST,index + 1,Long.class);
    }
}
